<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stock Candlestick Chart</title>
    <!-- Include ECharts library -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.0/dist/echarts.min.js"></script>
</head>
<body>
<div id="main" style="width: 100%; height: 600px;"></div>
<div>
    <form id="tradeForm">
        <label for="date">Date:</label>
        <input type="date" id="date" name="date">
        <label for="action">Action:</label>
        <select id="action" name="action">
            <option value="hold">Hold</option>
            <option value="buy">Buy</option>
            <option value="sell">Sell</option>
        </select>
        <label for="quantity">Quantity (multiples of 100):</label>
        <input type="number" id="quantity" name="quantity" min="100" step="100">
        <button type="submit">Submit Trade</button>
        <p>Remaining Funds: <span id="remainingFunds"></span></p>
        <p>Current Holdings: <span id="currentHoldings"></span></p>
    </form>
</div>

<script>
        // Initialize ECharts
        var chart = echarts.init(document.getElementById('main'));

        // Initialize data
        var stockData = [];
        var virtualFunds = 10000000; // Starting virtual funds
        var currentHoldings = 0; // Current number of stocks held
        var lastPurchaseDate = null; // Date of last stock purchase

        // Fetch data function
        function fetchData() {
            fetch("/stock_data")
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok ' + response.statusText);
                }
                return response.json();
            })
            .then(data => {
                stockData = data;
                renderChart(stockData);
            })
            .catch(error => {
                console.error('Error fetching data:', error);
            });
        }

        // Function to render chart
        function renderChart(data) {
            const dates = data.map(item => item.date);
            const openPrices = data.map(item => item.open);
            const closePrices = data.map(item => item.close);
            const lowPrices = data.map(item => item.low);
            const highPrices = data.map(item => item.high);

            const option = {
                title: {
                    text: 'Stock Candlestick Chart'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross'
                    },
                    formatter: function(params) {
                        var item = params[0];
                        return [
                            'Date: ' + item.name,
                            'Open: ' + item.data[0],
                            'Close: ' + item.data[1],
                            'Lowest: ' + item.data[2],
                            'Highest: ' + item.data[3]
                        ].join('<br/>');
                    }
                },
                xAxis: {
                    type: 'category',
                    data: dates,
                    axisLabel: {
                        formatter: function (value) {
                            return new Date(value).toISOString().split('T')[0];
                        }
                    },
                    scale: true,
                    boundaryGap : false
                },
                yAxis: {
                    type: 'value',
                    scale: true,
                    axisLabel: {
                        formatter: '{value}'
                    }
                },
                dataZoom: [
                    {
                        type: 'inside',
                        start: 0,
                        end: 100
                    },
                    {
                        start: 0,
                        end: 100,
                        handleSize: '80%',
                        handleStyle: {
                            color: '#fff',
                            shadowBlur: 3,
                            shadowColor: 'rgba(0, 0, 0, 0.6)',
                            shadowOffsetX: 2,
                            shadowOffsetY: 2
                        }
                    }
                ],
                series: [{
                    name: 'Stock Data',
                    type: 'candlestick',
                    data: data.map(item => [item.open, item.close, item.low, item.high]),
                    markPoint: {
                        symbol: 'pin',
                        data: [
                            {type: 'max', name: 'Highest'},
                            {type: 'min', name: 'Lowest'}
                        ]
                    },
                    markLine: {
                        symbol: ['none', 'none'],
                        data: [
                            {type: 'average', name: 'Average'}
                        ]
                    }
                }]
            };

            chart.setOption(option);
        }

        // Form submission handler
        document.getElementById('tradeForm').addEventListener('submit', function(event) {
            event.preventDefault();
            const formData = new FormData(event.target);
            const tradeDate = formData.get('date');
            const action = formData.get('action');
            const quantity = parseInt(formData.get('quantity'));

            // Check if quantity is multiples of 100
            if (quantity % 100 !== 0) {
                alert('Quantity must be multiples of 100.');
                return;
            }

            if (action === 'buy') {
                if (lastPurchaseDate === tradeDate) {
                    alert('You cannot sell on the same day as a purchase.');
                    return;
                }
                const cost = stockData[stockData.length - 1].close * quantity;
                if (cost > virtualFunds) {
                    alert('Not enough funds to buy.');
                    return;
                }
                virtualFunds -= cost;
                currentHoldings += quantity;
                lastPurchaseDate = tradeDate;
                console.log(`Buying ${quantity} stocks on ${tradeDate}`);
            } else if (action === 'sell') {
                if (currentHoldings === 0) {
                    alert('You do not own any stocks to sell.');
                    return;
                }
                if (lastPurchaseDate === tradeDate) {
                    alert('You cannot sell on the same day as a purchase.');
                    return;
                }
                // Implement sell logic (add feature)
                console.log(`Selling ${quantity} stocks on ${tradeDate}`);
            } else if (action === 'hold') {
                // User chooses to hold, no action needed
                console.log(`Holding stocks on ${tradeDate}`);
            }

            // Update remaining funds and current holdings display
            document.getElementById('remainingFunds').textContent = virtualFunds.toLocaleString();
            document.getElementById('currentHoldings').textContent = currentHoldings.toLocaleString();

            // For now, just re-render the chart with existing data
            renderChart(stockData);
        });

        // Initial fetch of data
        fetchData();
    </script>
</body>
</html>
